package org.pvt.gui;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import org.pvt.R;
import org.pvt.model.Models;
import org.pvt.model.data.PaymentDTO;

import java.util.List;

/**
 * @author Pavel Talanov
 */
public final class PaymentAdapter extends BaseAdapter {

    @NotNull
    private final AddExpenseActivity context;

    public PaymentAdapter(@NotNull AddExpenseActivity context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        return payments().size();
    }

    private List<PaymentDTO> payments() {
        return context.getPayments();
    }

    @Override
    public Object getItem(int i) {
        return payments().get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View paymentView = createPaymentView(viewGroup);
        PaymentDTO payment = payments().get(i);
        setAmountText(paymentView, payment);
        setPersonText(paymentView, payment);
        return paymentView;
    }

    private void setPersonText(@NotNull View paymentView, @NotNull final PaymentDTO payment) {
        TextView personText = (TextView) paymentView.findViewById(R.id.payment_person);
        String personName = Models.Person.getNameById(payment.personId, context);
        assert personName != null;
        personText.setText(personName);
    }

    private void setAmountText(@NotNull View paymentView, @NotNull final PaymentDTO payment) {
        final EditText amountEdit = (EditText) paymentView.findViewById(R.id.payment_amount);
        amountEdit.setText(UIUtils.floatToText(payment.amount, false));
        amountEdit.setFilters(new InputFilter[]{new DecimalDigitsInputFilter()});
        amountEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //do noting
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //do nothing
            }

            @Override
            public void afterTextChanged(Editable editable) {
                payment.amount = UIUtils.textToFloat(amountEdit.getText().toString());
            }
        });
    }

    private View createPaymentView(ViewGroup viewGroup) {
        LayoutInflater inflater = LayoutInflater.from(context);
        return inflater.inflate(R.layout.payment, null);
    }

}
